<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Workerman\Worker;
use \GatewayWorker\Lib\Gateway;
require_once 'vendor/autoload.php';
// 初始化一个worker容器，监听1234端口

class Push extends CI_Controller {

	private $earth_radius = 6371;//地球半径，平均半径为6371km;
	static $hours;

	public function __construct()
	{
		parent::__construct();
//		$this->load->model("User_model");
//		$this->load->model('Cash_model');
		$this->load->model('Device_model');
		$this->load->model('Push_model');
		$this->load->helper('url');
		$this->createPrice();
	}

	public function createPrice()
	{
		for($i = 0; $i < 24; $i++){
			if($i >= 0 && $i < 7){			//0点~7点
				self::$hours[$i]['price'] = 240;
			}elseif($i >= 7 && $i < 10){	//7点~10点
				self::$hours[$i]['price'] = 1680;
			}elseif($i >= 10 && $i < 12){	//10点~12点
				self::$hours[$i]['price'] = 480;
			}elseif($i == 12){				//12点~13点
				self::$hours[$i]['price'] = 1680;
			}elseif($i >= 13 && $i < 16){	//13点~16点
				self::$hours[$i]['price'] = 480;
			}elseif($i == 16){				//16点~17点
				self::$hours[$i]['price'] = 1680;
			}elseif($i >= 17 && $i < 20){	//17点~20点
				self::$hours[$i]['price'] = 2640;
			}elseif($i == 20){				//20点~21点
				self::$hours[$i]['price'] = 1680;
			}else{							//21点~0点
				self::$hours[$i]['price'] = 480;
			}
		}
	}

	/**
	 * 点发推送
	 */
	public function index()
	{
		// 建立socket连接到内部推送端口
		$client = stream_socket_client('tcp://127.0.0.1:2701', $errno, $errmsg, 1);
// 推送的数据，包含uid字段，表示是给这个uid推送
//$data = json_decode($_GET['data'],true);
//$data = array('uid'=>'w', 'percent'=>'88%');
// 发送数据，注意5678端口是Text协议的端口，Text协议需要在数据末尾加上换行符
//fwrite($client, json_encode($data)."\n");
		/* $de_data = json_decode($_GET['data'],true);
		$data['msg'] = iconv( "UTF-8", "gb2312//IGNORE" , $de_data['msg']);
		$data['deviceId'] = iconv( "UTF-8", "gb2312//IGNORE" , $de_data['deviceId']);
		$data['endTime'] = iconv( "UTF-8", "gb2312//IGNORE" , $de_data['endTime']);*/
//		var_dump($_GET['data']);
		//$data = '{"deviceId":"09BB7e7tfhwixAvq8lWniawQTlpRDLWc","msg":"请播放一条广告：用飘柔就是那么自信！~","endTime":"1483027200"}';
		fwrite($client, trim($_GET['data'])."\n");
// 读取推送结果
		echo fread($client, 8192);
	}

	/**
	 * 圈发
	 * @return bool|string
	 */
	public function roundPush()
	{
		$allAds = $this->Push_model->getAllAd();	//获取所有需要推送的广告
		if(empty($allAds)){return false;}
		foreach ($allAds as $adInfo){
			$this->roundPushOperate($adInfo);	//获取需投放车辆信息 拼装成广告内容 并推送
		}
	}


	/**
	 *计算某个经纬度的周围某段距离的正方形的四个点
	 *
	 *@param lng float 经度
	 *@param lat float 纬度
	 *@param distance float 该点所在圆的半径，该圆与此正方形内切，默认值为0.5千米
	 *@return array 正方形的四个点的经纬度坐标
	 */
	public function returnSquarePoint($lng, $lat,$distance = 1){

		$dlng =  2 * asin(sin($distance / (2 * $this->earth_radius)) / cos(deg2rad($lat)));
		$dlng = rad2deg($dlng);

		$dlat = $distance/$this->earth_radius;
		$dlat = rad2deg($dlat);

		return array(
			'left-top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
			'right-top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
			'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
			'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
		);
	}

	/**
	 * 获取需投放车辆信息
	 * @param $lng
	 * @param $lat
	 * @param $range
	 * @return bool
	 */
	public function roundPushOperate($data)
	{
		date_default_timezone_set('Asia/Shanghai');
		$time = time();
		$h = intval(date('H',$time));	//当前所处小时
		$squares = $this->returnSquarePoint($data['lng'],$data['lat'],$data['range']);	//计算某个经纬度的周围某段距离的正方形的四个点
		$carsInfo = $this->Push_model->getRoundCars($squares,$data['cars']);	//查询广告投放范围内的车辆
		if(empty($carsInfo)){
			return false;
		}
		// 建立socket连接到内部推送端口
		$client = stream_socket_client('tcp://127.0.0.1:2701', $errno, $errmsg, 1);
		foreach ($carsInfo as $car){
			//{"type":"1","id":"09BB7e7tfhwixAvq8lWniawQTlpRDLWc","ad":"点发","time":"100"}
			$adInfo = [];
			$adInfo = [
				'type' => '2',                			//圈发
				'id'   => $car['device_id'],    		//设备id
				'ad'   => $data['ad_info'],        		//广告内容
				'time' => 300,                			//广告时间
			];
			//推送
			fwrite($client, json_encode($adInfo,JSON_UNESCAPED_UNICODE)."\n");
			// 读取推送结果
			$result = fread($client, 8192);
			var_dump('推送结果'.$result,'推送内容：'.json_encode($adInfo,JSON_UNESCAPED_UNICODE));

			$atb = $data['atb'] ? : 'bin';     	//属性  公益：pub  商业：bin
			if($atb == 'bin'){	//商业广告 参与计费
				$isGiveMoney = $this->Device_model->isGiveMoney($car['device_id']);	//设备的位置变化是否满足支付广告费（半小时内位移>10m）
				if($isGiveMoney == false){	//不满足条件，只播放广告，不计费
					continue;
				}
				$addData = [
					'uid'=>$data['uid'],	//投放广告人id
					'ad_id'=>$data['id'],	//广告id
					'device_id'=>$car['device_id'],	//设备id
					'device_uid'=>$car['uid'],	//设备主人用户id
					'ad_info'=>$data['ad_info'],	//广告内容
					'cash'=>(self::$hours[$h]['price']/60)*(300/60),	//此次广告推送金额  一次推送广告时间为5分钟
					'lng'=>$data['lng'],	//当前车辆经度坐标
					'lat'=>$data['lat'],	//当前车辆纬度坐标
					'create_time'=>$time,
					'update_time'=>$time,
				];
				if($result == "ok\n"){
					$addData['status'] = 1;	//广告发送状态 1：成功  2：失败
				}else{
					$addData['status'] = 0;	//广告发送状态 1：成功  2：失败
				}
				$this->Push_model->addPushAdRecord($addData,$car['device_id']);	//添加推送广告结果记录
			}
		}
		return true;
	}


	
	
}
